<template>
  <div class="container" ref="container">
    <button @click="handleLongTask">测试长任务</button>
    <button @click="upload">请求</button>
    <el-upload
      class="avatar-uploader"
      action="http://192.168.3.153:5000/recognize"
      :show-file-list="false"
      name="files"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
    >
      <img v-if="imageUrl" :src="imageUrl" class="avatar" />
      <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
    </el-upload>
  </div>
</template>
<script setup lang="ts">
import { onMounted, ref } from 'vue'
let imageUrl = ref('')
const container = ref<HTMLElement | null>(null)
const handleAvatarSuccess = (res, file) => {
  imageUrl.value = URL.createObjectURL(file.raw)
}
const beforeAvatarUpload = (file) => {
  // const isJPG = file.type === 'image/jpeg'
  // const isLt2M = file.size / 1024 / 1024 < 2
  // if (!isJPG) {
  //   alert('上传头像图片只能是 JPG 格式!')
  // }
  // if (!isLt2M) {
  //   alert('上传头像图片大小不能超过 2MB!')
  // }
  // return isJPG && isLt2M
  return true
}
const upload = () => {}

const handleLongTask = async () => {
  for (let i = 0; i < 10; i++) {
    // 减少循环次数以避免过长等待，实际使用中可根据需要调整
    await task(async () => {
      await innerHtml(container.value!, `Task ${i + 1}`)
    })
  }
}

const innerHtml = async (container: HTMLElement, text: string) => {
  const p = document.createElement('p')
  p.innerText = text
  container.appendChild(p)
  // 模拟UI更新后的等待时间
  await new Promise((resolve) => setTimeout(resolve, 500))
}

const task = async (fun: () => Promise<void>) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      fun().then(resolve)
    }, 10000) // 模拟每个任务的执行时间
  })
}

onMounted(() => {
  // 可以在此处进行组件挂载后的初始化操作，但不需要启动长任务
})
</script>
<style scoped lang="less">
.container {
  width: 100%;
  height: 100%;
}
</style>

